<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop" ref="buttondiv">
          <table style="width: 100%; font-size: 12px;" border="0">
              <col style="width: 6%;" />
              <col style="width: 8%;" />
              <col style="width: 86%;" />
              <tr>
                  <td>报告单元</td>
                  <td>
                      <rm-ddl-rptunit :appendtobody="true" v-model="rptunitval" @change="RptUnitChange" filterable
                          :clearable="false" :defaultflag="'1'" with="100%"></rm-ddl-rptunit>
                  </td>
                  <td>
                      <el-radio-group v-model="radio" @change="btnQuery" style="font-size: 12px">
                          <el-radio v-model="radio" label="0">实验室意见</el-radio>
                          <el-radio v-model="radio" label="1">文字描述 1</el-radio>
                          <el-radio v-model="radio" label="2">文字描述2</el-radio>
                          <el-radio v-model="radio" label="A">备用1</el-radio>
                          <el-radio v-model="radio" label="B">备用2</el-radio>
                          <el-radio v-model="radio" label="C">备用3</el-radio>
                          <el-radio v-model="radio" label="D">备用4</el-radio>
                          <el-radio v-model="radio" label="E">备用5</el-radio>
                          <el-radio v-model="radio" label="M">待查原因</el-radio>
                          <el-radio v-model="radio" label="G">图片描述</el-radio>
                      </el-radio-group>
                  </td>
              </tr>
              <tr>
                  <td colspan="3" align="right">
                      <el-button icon="el-icon-search" type="primary" @click="btnQuery()" v-has="'PINQUERY'">查询
                      </el-button>
                      <el-button @click="btnAdd" icon="el-icon-plus" v-has="'PADD'">新增</el-button>
                      <el-button @click="btnDelete" icon="el-icon-delete" v-has="'PDELETE'">删除</el-button>
                      <el-button @click="btnSave" icon="el-icon-document-add">保存</el-button>
                      <el-button icon="el-icon-document-copy" @click="copyData">复制</el-button>
                      <el-button @click="btnExport" icon="el-icon-files" v-has="'PEXPORT'">导出</el-button>
                  </td>
              </tr>
          </table>
      </div>
      <div class="pagecenter">
          <div class="middle-center" style="height:100%;">
              <vxe-table :loading="bLoading" :data.sync="tableData" :row-class-name="rowClassName"
                  @current-change="currentChangeEvent" border fit :mouse-config="{ selected: true }"
                  :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, showIcon: false }"
                  @edit-actived="CellActive" :keyboard-config="keyConfig" height="auto" header-align="center"
                  @edit-closed="EditChange" highlight-current-row highlight-hover-row ref="xTable" resizable
                  show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe>
                  <vxe-table-column field="seq" title="序号" align="center" width="40"
                      :edit-render="{ name: 'input', autoselect: true,events: {change: seqChange}}" sortable> <template
                          v-slot:header="{ column }">
                          <span style="color:#F56C6C;">序号</span></template>
                  </vxe-table-column>
                  <vxe-table-column field="txtinfo" title="文字描述" width="400" sortable> <template
                          v-slot:header="{ column }">
                          <span style="color:#F56C6C;">文字描述</span></template><template v-slot="{ row, rowIndex }">
                          <el-input style="print" v-model="row.txtinfo" type="textarea" autosize
                              @focus="Focus($event)" @change="TextChange(row)"></el-input>
                      </template></vxe-table-column>
                  <vxe-table-column field="inputcode" title="快速输入码" width="150" sortable
                      :edit-render="{ name: 'input', autoselect: true }">
                  </vxe-table-column>
                  <vxe-table-column field="txttitle" title="标题" width="160" sortable
                      :edit-render="{ name: 'input', autoselect: true }">
                  </vxe-table-column>
              </vxe-table>
          </div>
      </div>
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
          <span><span class="el-icon-info">确定删除该条记录吗？</span></span>
          <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="SubmitDel">确 定</el-button>
              <el-button @click="dialogVisible = false">取 消</el-button>
          </span>
      </el-dialog>

      <el-dialog width="550px" top="2px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false"
          title="复制文字描述" :visible.sync="popCopyVisible">
          <div style="width: 100%; position: relative">
              <table style="font-size: 12px; white-space: nowrap; width: 100%">
                  <tr>
                      <td style="color: red;">选择复制类型</td>
                      <td>
                          <el-select v-model="copyType" style="width: 400px">
                              <el-option key="current" :label=copyOptopnName value="current">
                              </el-option>
                              <el-option key="all" label="复制所有类型的描述" value="all">
                              </el-option>
                          </el-select>
                      </td>
                  </tr>
                  <tr>
                      <td style="color: red;">复制到其他报告单元</td>
                      <td>
                          <el-input width="400px" v-model="this.copy_rptids.defaultvaluename" ref="muilt_instrids"
                              key="instrids" placeholder="多选双击开窗" readonly
                              @dblclick.native="DialogSql(copy_rptids)">
                              <el-button slot="append" @click.native="DialogSql(copy_rptids)">选择</el-button>
                          </el-input>
                      </td>
                  </tr>
                  <tr>
                      <td>
                          &nbsp;
                      </td>
                      <td>
                          &nbsp;
                      </td>
                  </tr>
                  <tr>
                      <td>
                      </td>
                      <td style="width: 300px; text-align: right">
                          <el-button @click="btnok()" icon="el-icon-check">确认</el-button>
                          <el-button @click="cancelCopy()" icon="el-icon-close">取消</el-button>
                      </td>
                  </tr>
              </table>
          </div>
      </el-dialog>

      <!--多选弹窗--->
      <el-dialog width="900px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false"
          :title="multichktitle" :visible.sync="dialogMultipleVisible" :destroy-on-close="true"
          v-if="dialogMultipleVisible">
          <rm-SqlMultiple :leftOption="LeftListOptions" :rightOption="RightListOptions" :name="fieldname"
              @change="closedialog"></rm-SqlMultiple>
      </el-dialog>

  </div>
</template>

<script>
import XLSX from "xlsx";
import XE from "xe-utils";
import FileSaver from "file-saver";
export default {
  name: "LIS139",
  data() {
      return {
          message: "",
          selectrow: [],
          curselectrow: "",
          actionindex: 0,
          tempindex: 0,
          radio: "0",
          tableData: [],
          bLoading: true,
          bFirstLoading: true,
          dialogVisible: false,
          rptunitval: "",
          rptunitname: "",
          tablePage: {
              pageSize: 15,
          },
          keyConfig: {
              isArrow: true,
              isDel: true,
              isTab: true,
              isEdit: true,
          },
          tableColumn: [
              { title: "序号", field: "seq" },
              { title: "文字描述", field: "txtinfo" },
              { title: "快速输入码", field: "inputcode" },
              { title: "标题", field: "txttitle" },
          ],
          popCopyVisible: false,
          copyOptopnName: "仅复制实验室意见",
          copyType: "current",
          copy_rptids: {},
          rptOption: [],
          dialogMultipleVisible: false,
      };
  },
  created() {
      this.btnQuery(); //初始化主列表
  },
  computed: {
      autoSeq() {
          let len = this.$refs.xTable.tableData.length;
          return (len + 1) * 10;
      },
  },
  updated() {
      if (this.bFirstLoading) {
          let currentrow = "";
          if (this.actionindex != 0) {
              //新增，修改，删除
              if (this.actionindex == 3) {
                  //如果是删除
                  if (this.tempindex > 0) {
                      currentrow = this.$refs.xTable.getData(this.tempindex - 1);
                  } else {
                      currentrow = this.$refs.xTable.getData(0);
                  }
              } else {
                  //新增或修改
                  if (this.curselectrow && this.curselectrow != "") {
                      this.$nextTick(() => {
                          let row = this.curselectrow;
                          var alld = this.$refs.xTable.tableData;
                          for (var i = 0; i < alld.length; i++) {
                              if (alld[i].codeno == row.codeno) {
                                  this.tempindex = i;
                                  break;
                              }
                          }
                          currentrow = this.$refs.xTable.getData(this.tempindex);
                      });
                  } else {
                      currentrow = this.$refs.xTable.getData(0);
                  }
              }
          } else {
              //查询
              currentrow = this.$refs.xTable.getData(0);
              this.actionindex = 2;
              this.curselectrow = currentrow;
          }
          this.$nextTick(() => {
              if (currentrow) {
                  this.bFirstLoading = false;
                  this.$refs.xTable.setCurrentRow(currentrow);
                  this.message = currentrow.codena;
              }
          });
      }
  },
  methods: {
      btnQuery() {
          this.bLoading = true;
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS139",
                  method: "post",
                  data: {
                      action: "query",
                      infotype: this.radio,
                      rptunitid: this.rptunitval,
                  },
              })
              .then((res) => {
                  this.rptOption = res.rptunitOption;
                  this.tableData = res.RData.Data;
                  this.bLoading = false;
                  this.bFirstLoading = true;
              })
              .catch((e) => {
                  this.bLoading = false;
                  console.log("error", e);
              });
      },
      rowClassName({ row, rowIndex }) {
          let isDirty = this.$refs.xTable.hasRowChange(row);
          if (isDirty) {
              return "row-modify";
          }
          if (this.$refs.xTable.hasRowInsert(row)) {
              return "row-new";
          }
      },
      currentChangeEvent({ row, $rowIndex }) {
          this.message = row.codena;
          this.actionindex = 2; //修改
          this.tempindex = $rowIndex;
          this.curselectrow = row;
      },
      btnAdd() {
          let initdata = {
              rptunitid: this.rptunitval,
              infotype: this.radio,
          };
          this.$refs.xTable
              .insertAt(
                  {
                      //报告单元，类型
                      rptunitid: this.rptunitval,
                      infotype: this.radio,
                      //表格显示
                      seq: this.autoSeq,
                      txtinfo: "",
                      inputcode: "",
                      txttitle: "",
                  },
                  -1
              )
              .then(({ row }) => {
                  this.FunscrollY();
                  this.actionindex = 1;
              });
      },
      copyData() {
          this.infotype = this.radio;
          switch (this.radio) {
              case "0":
                  this.copyOptopnName = "仅复制实验室意见";
                  break;
              case "1":
                  this.copyOptopnName = "仅复制文字描述 1";
                  break;
              case "2":
                  this.copyOptopnName = "仅复制文字描述2";
                  break;
              case "A":
                  this.copyOptopnName = "仅复制备用1";
                  break;
              case "B":
                  this.copyOptopnName = "仅复制备用2";
                  break;
              case "C":
                  this.copyOptopnName = "仅复制备用3";
                  break;
              case "D":
                  this.copyOptopnName = "仅复制备用4";
                  break;
              case "E":
                  this.copyOptopnName = "仅复制备用5";
                  break;
              case "M":
                  this.copyOptopnName = "仅复制待查原因";
                  break;
              case "G":
                  this.copyOptopnName = "仅复制图片描述";
                  break;
          }

          this.popCopyVisible = true;
      },
      seqChange({row,rowindex},val){
          var seq = val.target.value;
          var pattern = /^[0-9]*$/;
          if(!pattern.test(seq)){
              setTimeout(() => {
                  row.seq="";
              }, 1);
          }
      },
      btnok() {
          if (!this.copyType) {
              this.$message.error("错误：选择复制类型必填");
              return false;
          }
          if (!this.copy_rptids.defaultvalue) {
              this.$message.error("错误：复制到其他报告单元必填");
              return false;
          }
          this.popCopyVisible = false;

          this.$tool
              .request({
                  url: "LIS/LIS1/LIS139",
                  method: "post",
                  data: {
                      action: "saveCopy",
                      infotype: this.radio,
                      rptunitid: this.rptunitval,
                      copyType: this.copyType,
                      copy_rptids: this.copy_rptids.defaultvalue,
                  }
              })
              .then(res => {
                  if (res.errcode == 1) {
                      this.$message.success("复制成功！");
                  } else {
                      this.$message.error("错误：" + res.errmsg);
                  }
              })
      },
      cancelCopy() {
          this.popCopyVisible = false;
      },
      //多选弹窗关闭this.rptOption
      closedialog(value, code, valuename) {
          if (value != "close") {
              this.copy_rptids.defaultvalue = value;
              this.copy_rptids.defaultvaluename = valuename;
          }
          this.dialogMultipleVisible = false;
      },
      //sql多选弹窗
      DialogSql(item) {
          this.fieldname = "检验仪器";
          this.multichktitle = "检验仪器";

          var rowlist = [];
          if (item.defaultvalue) rowlist = item.defaultvalue.split(",");
          this.LeftListOptions = this.rptOption.filter(item => rowlist.indexOf(item.data + "") == -1);
          this.RightListOptions = this.rptOption.filter(item => rowlist.indexOf(item.data + "") > -1);

          this.dialogMultipleVisible = true;
      },
      FunscrollY() {
          this.$nextTick(() => {
              var alldataLen = this.$refs.xTable.tableData.length;
              let L = this.$refs.xTable.tableData[alldataLen - 1];
              this.$refs.xTable.setCurrentRow(L);
              this.$refs.xTable.setActiveRow(L, "txtinfo");
              this.$refs.xTable.scrollToRow(L);
          });
      },
      btnDelete() {
          if (this.$refs.xTable.tableData.length > 0) {
              this.dialogVisible = true;
          }
      },
      SubmitDel() {
          let delrow = this.$refs.xTable.getCurrentRow();
          if (delrow) {
              var alld = this.$refs.xTable.tableData;
              var rowindex = alld.indexOf(delrow);
              this.$refs.xTable.remove(delrow);
              this.actionindex = 3; //删除
              let havedata = this.$refs.xTable.tableData;
              if (havedata.length > 0) {
                  if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                  this.tempindex = rowindex;
                  let selectrow = havedata[rowindex];
                  this.$refs.xTable.setCurrentRow(selectrow);
                  this.message = selectrow.alarmno;
              }
          } else {
              this.$message({
                  message: "请选择要删除的记录！",
                  type: "warning",
              });
          }
          this.dialogVisible = false;
      },
      EditChange({ row, column }) {
          if (column.property == "txtinfo") {
              row.inputcode = this.$pub.CreateInputcode(row.txtinfo, this, 16);
          }
          if (row.seq == ("" || null)) {
              row.rptunitid = this.rptunitval;
              row.infotype = this.radio;
          }
      },
      Getinputcode(row) {
          row.inputcode = this.$pub.CreateInputcode(row.txtinfo, this, 16);
      },
      btnSave() {
          let date = this.$refs.xTable.getTableData().fullData;
          if (date.length == 0) {
              return false;
          }
          // for (let i = 0, len = date.length; i < len; i++) {
          //     let tempseq = (i + 1) * 10;
          //     if (tempseq !== date[i].seq) {
          //         date[i].seq = tempseq;
          //     }
          // }
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS139",
                  method: "post",
                  data: {
                      action: "save",
                      urec: this.$refs.xTable.getRecordset(),
                      infotype: this.radio,
                      rptunitid: this.rptunitval,
                  },
              })
              .then((response) => {
                  if (response.errcode == "1") {
                      this.btnQuery();
                      this.$message({
                          message: "保存成功！",
                          type: "success",
                      });
                  } else {
                      this.$message({
                          message: "保存失败！" + response.errmsg,
                          type: "warning",
                      });
                  }
              });
      },
      btnExport() {
          let data = this.getExportData();
          let book = XLSX.utils.book_new();
          let sheet = XLSX.utils.json_to_sheet(data, { skipHeader: true });
          XLSX.utils.book_append_sheet(book, sheet);
          let wbout = XLSX.write(book, {
              bookType: "xlsx",
              bookSST: false,
              type: "binary",
          });
          let blob = new Blob([this.toBuffer(wbout)], {
              type: "application/octet-stream",
          });
          // 保存导出
          FileSaver.saveAs(blob, "LIS139 报告单元文字描述/评语.xlsx");
      },
      toBuffer(wbout) {
          let buf = new ArrayBuffer(wbout.length);
          let view = new Uint8Array(buf);
          for (let index = 0; index !== wbout.length; ++index) view[index] = wbout.charCodeAt(index) & 0xff;
          return buf;
      },
      getExportData() {
          let datas = this.tableData;
          var allcolumns = this.$refs.xTable.getColumns();
          var tableColumn = [];
          for (let i = 0; i < allcolumns.length; i++) {
              tableColumn.push({
                  field: allcolumns[i].property,
                  title: allcolumns[i].title,
              });
          }
          let columns = tableColumn.filter((item) => item.field);
          let headers = [columns.map((item) => item.title)];
          return headers.concat(
              datas.map((row) => {
                  return columns.map((column) => {
                      return row[column.field];
                  });
              })
          );
      },
      CellActive({ row, columnIndex, column }) {
          this.$refs.xTable.setCurrentRow(row);
          this.actionindex = 2; //修改
          this.tempindex = this.$refs.xTable.getRowIndex(row);
      },
      RptUnitChange(val, name) {
          this.copy_rptids={};
          this.rptunitval = val;
          this.rptunitname = name;
          this.btnQuery();
      },
      Focus(event) {
          event.currentTarget.select();
      },
      TextChange(row) {
          this.Rep(row);
          this.Getinputcode(row);
      },
      Rep(row) {
          var reg = /\n(\n)*( )*(\n)*\n/g;
          row.txtinfo = row.txtinfo.replace(reg, "\n");
      },
  },
};
</script>

<style scoped>
.pagetop {
  width: 100%;
  height: 72px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 77px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 0px;
  overflow: auto;
}

.search-title {
  margin: 0 5px 0 20px;
  font-size: 12px;
}

.top-deal {
  right: 5px;
  position: absolute;
  top: 5px;
  display: flex;
  align-items: center;
}

::v-deep tr.vxe-body--row.row-modify {
  color: blue;
}

::v-deep tr.vxe-body--row.row-new {
  color: #cc6600;
}

::v-deep.el-radio__label {
  font-size: 12px;
  padding-left: 10px;
}

::v-deep.vxe-body--row,
.vxe-body--row.row--current,
.vxe-body--row.row--hover {
  vertical-align: top;
}

::v-deep.print {
  white-space: pre-line;
}

::v-deep.el-radio {
  margin-right: 8px !important;
}

::v-deep.el-radio__label {
  padding-left: 5px;
}
</style>
